package com.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.Query;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.mall.dto.*;
import com.mall.entity.OmsOrder;
import com.mall.entity.OmsOrderItem;
import com.mall.entity.OmsOrderOperateHistory;
import com.mall.mapper.OmsOrderItemMapper;
import com.mall.mapper.OmsOrderMapper;
import com.mall.mapper.OmsOrderOperateHistoryMapper;
import com.mall.service.OmsOrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author zzx
 * @since 2022-06-15
 */
@Service
public class OmsOrderServiceImpl extends ServiceImpl<OmsOrderMapper, OmsOrder> implements OmsOrderService {

    private static final Logger LOGGER = LoggerFactory.getLogger(PmsProductServiceImpl.class);
    @Autowired
    private OmsOrderMapper orderMapper;
    @Autowired
    private OmsOrderOperateHistoryMapper orderOperateHistoryMapper;
    @Autowired
    private OmsOrderItemMapper orderItemMapper;

    @Override
    public boolean Save(OmsOrder order) {
        if(order.getId() == null)
        {
            return orderMapper.insert(order) > 0;
        }else{
            return  orderMapper.updateById(order) > 0;
        }
    }

    @Override
    public List<OmsOrder> list(OmsOrderQueryParam queryParam, Integer pageSize, Integer pageNum) {
        PageHelper.startPage(pageNum, pageSize);
        return orderMapper.getList(queryParam);
    }

    @Override
    public int delivery(List<OmsOrderDeliveryParam> deliveryParamList) {
        //批量发货
        int count = orderMapper.delivery(deliveryParamList);
        //添加操作记录
        List<OmsOrderOperateHistory> operateHistoryList = deliveryParamList.stream()
                .map(omsOrderDeliveryParam -> {
                    OmsOrderOperateHistory history = new OmsOrderOperateHistory();
                    history.setOrderId(omsOrderDeliveryParam.getOrderId());
                    history.setCreateTime(new Date());
                    history.setOperateMan("后台管理员");
                    history.setOrderStatus(2);
                    history.setNote("完成发货");
                    return history;
                }).collect(Collectors.toList());
        ExecutorService executorService = Executors.newFixedThreadPool(operateHistoryList.size());

        operateHistoryList.forEach(operateHistory -> {
            executorService.execute(() -> {
                orderOperateHistoryMapper.insert(operateHistory);
            });
        });
        try {
            executorService.awaitTermination(10, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            LOGGER.error("线程异常", e);
        }
        executorService.shutdown();
        return count;
    }

    @Override
    public int close(List<Long> ids, String note) {
        OmsOrder record = new OmsOrder();
        record.setStatus(4);
        QueryWrapper<OmsOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", ids).eq("status", 0);
        int count = update(record, queryWrapper) ? 1 : 0;
        List<OmsOrderOperateHistory> historyList = ids.stream().map(orderId -> {
            OmsOrderOperateHistory history = new OmsOrderOperateHistory();
            history.setOrderId(orderId);
            history.setCreateTime(new Date());
            history.setOperateMan("后台管理员");
            history.setOrderStatus(4);
            history.setNote("订单关闭:" + note);
            return history;
        }).collect(Collectors.toList());
        ExecutorService executorService = Executors.newFixedThreadPool(historyList.size());

        historyList.forEach(operateHistory -> {
            executorService.execute(() -> {
                orderOperateHistoryMapper.insert(operateHistory);
            });
        });
        try {
            executorService.awaitTermination(10, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            LOGGER.error("线程异常", e);
        }
        executorService.shutdown();
        return count;
    }

    @Override
    public int delete(List<Long> ids) {
        OmsOrder record = new OmsOrder();
        record.setDeleteStatus(1);
        QueryWrapper<OmsOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", ids).eq("delete_status", 0);
        return update(record, queryWrapper) ? 1 : 0;
    }

    @Override
    public OmsOrderDetail detail(Long id) {
        return orderMapper.getDetail(id);
    }

    @Override
    public int updateReceiverInfo(OmsReceiverInfoParam receiverInfoParam) {
        OmsOrder order = new OmsOrder();
        order.setId(receiverInfoParam.getOrderId());
        order.setReceiverName(receiverInfoParam.getReceiverName());
        order.setReceiverPhone(receiverInfoParam.getReceiverPhone());
        order.setReceiverPostCode(receiverInfoParam.getReceiverPostCode());
        order.setReceiverDetailAddress(receiverInfoParam.getReceiverDetailAddress());
        order.setReceiverProvince(receiverInfoParam.getReceiverProvince());
        order.setReceiverCity(receiverInfoParam.getReceiverCity());
        order.setReceiverRegion(receiverInfoParam.getReceiverRegion());
        order.setModifyTime(new Date());
        int count = updateById(order) ? 1 : 0;
        //插入操作记录
        OmsOrderOperateHistory history = new OmsOrderOperateHistory();
        history.setOrderId(receiverInfoParam.getOrderId());
        history.setCreateTime(new Date());
        history.setOperateMan("后台管理员");
        history.setOrderStatus(receiverInfoParam.getStatus());
        history.setNote("修改收货人信息");
        orderOperateHistoryMapper.insert(history);
        return count;
    }

    @Override
    public int updateMoneyInfo(OmsMoneyInfoParam moneyInfoParam) {
        OmsOrder order = new OmsOrder();
        order.setId(moneyInfoParam.getOrderId());
        order.setFreightAmount(moneyInfoParam.getFreightAmount());
        order.setDiscountAmount(moneyInfoParam.getDiscountAmount());
        order.setModifyTime(new Date());
        int count = updateById(order) ? 1 : 0;
        //插入操作记录
        OmsOrderOperateHistory history = new OmsOrderOperateHistory();
        history.setOrderId(moneyInfoParam.getOrderId());
        history.setCreateTime(new Date());
        history.setOperateMan("后台管理员");
        history.setOrderStatus(moneyInfoParam.getStatus());
        history.setNote("修改费用信息");
        orderOperateHistoryMapper.insert(history);
        return count;
    }

    @Override
    public int updateNote(Long id, String note, Integer status) {
        OmsOrder order = new OmsOrder();
        order.setId(id);
        order.setNote(note);
        order.setModifyTime(new Date());
        int count = updateById(order) ? 1 : 0;
        OmsOrderOperateHistory history = new OmsOrderOperateHistory();
        history.setOrderId(id);
        history.setCreateTime(new Date());
        history.setOperateMan("后台管理员");
        history.setOrderStatus(status);
        history.setNote("修改备注信息：" + note);
        orderOperateHistoryMapper.insert(history);
        return count;
    }

    @Override
    public Long getMax() {
        return orderMapper.getMaxId();
    }

    public List<FrontOrderDto> getOrderByMemberId(Long id, int pageSize, int pageNum) {
        PageHelper.startPage(pageNum, pageSize);
        QueryWrapper<OmsOrderItem> queryWrapper = new QueryWrapper<>();
        List<FrontOrderDto> orderDtoList = orderMapper.getFrontOrderList(id);
        List<Long> orderIds = orderDtoList.stream().map(orderDto -> orderDto.getId()).collect(Collectors.toList());
        queryWrapper.in("order_id", orderIds);
        List<OmsOrderItem> orderItemList = orderItemMapper.selectList(queryWrapper);
        //将orderItemList放入orderDtoList中
        orderDtoList.forEach(orderDto -> {
            List<OmsOrderItem> orderItemList1 = orderItemList.stream().filter(orderItem -> orderItem.getOrderId().equals(orderDto.getId())).collect(Collectors.toList());
            orderDto.setOrderItemList(orderItemList1);
        });
        return orderDtoList;
    }

    @Override
    public int confirm(Long id) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        UpdateWrapper<OmsOrder> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id);
        updateWrapper.set("confirm_status", 1);
        updateWrapper.set("modify_time", sdf.format(new Date()));
        updateWrapper.set("receive_time", sdf.format(new Date()));
        updateWrapper.set("status", 3);
        return update(updateWrapper) ? 1 : 0;
    }

    @Override
    public int pay(Long id,int payType) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        UpdateWrapper<OmsOrder> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id);
        updateWrapper.set("status", 1);
        updateWrapper.set("payment_time", sdf.format(new Date()));
        updateWrapper.set("pay_type", payType);
        return update(updateWrapper) ? 1 : 0;
    }
}
